import { tokenKey, baseUrl } from '/config';
let storedOptions = {};
export const request = (options) => {
    const { url = '', method = "GET", data, headers = {} } = options;
    const storageData = my.getStorageSync({ key: tokenKey });
    const { token } = storageData.data || {};
    if (token) headers[tokenKey] = `Bearer ${token}`;
    return new Promise((resolve, reject) => {
        my.request({
            url: baseUrl + url,
            method,
            data,
            headers
        }).then(async res => {
            if (res.status >= 200 && res.status <= 300) {
                const { code, message } = res.data;
                if (code === 401) {
                    if (url.includes('refreshToken')) {
                        const pages = getCurrentPages();
                        const currentPage = pages[pages.length - 1];
                        let cb = () => null;
                        if (currentPage.data.hasOwnProperty('userInfo')) {
                            cb = userInfo => currentPage.setData({ userInfo });
                        }
                        await getApp().login(cb);
                    } else {
                        const storageData = my.getStorageSync({
                            key: tokenKey
                        });
                        const { refreshToken } = storageData || {};
                        const { code, data: { userInfo, ...tokenInfo } = {} } = await request.post(
                            '/miniapp/user/refreshToken', { refreshToken });
                        if (code === 200) {
                            my.setStorageSync({
                                key: tokenKey,
                                data: tokenInfo
                            });
                            my.setStorageSync({
                                key: 'userInfo',
                                data: userInfo
                            });
                            return request(options);
                        }
                    }
                } else if (code === 200) {
                    resolve(res.data);
                } else {
                    resolve(res.data);
                    my.showToast({
                        type: 'fail',
                        content: message
                    });
                }
            } else {
                reject(res.data);
            }
        }).catch(err => {
            console.log(err);
            err && my.showToast({
                type: 'fail',
                content: err.errorMessage || '请求失败'
            });
            reject(err.errorMessage);
        })
    })
}
request.get = (url, { params, ...options } = {}) => request({ url, data: params, ...options });
request.post = (url, data, options = {}) => request({ url, data, method: 'POST', ...options });
request.delete = (url, { data, ...options } = {}) => request({ url, data, method: 'DELETE', ...options });